package com.geek.chat.server.operation.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geek.chat.common.constant.Constants;
import com.geek.chat.common.constant.ResultCodeEnum;
import com.geek.chat.common.protobuf.ProtoMsg.LoginInfo;
import com.geek.chat.common.protobuf.ProtoMsg.Message;
import com.geek.chat.common.protobuf.builder.ProtobufBuilder;
import com.geek.chat.common.session.Session;
import com.geek.chat.server.operation.AbstractOperation;
import com.geek.chat.server.session.SessionMap;

public class AuthOperation extends AbstractOperation {
	private Logger logger = LoggerFactory.getLogger(AuthOperation.class);
	@Override
	public Integer op() {
		return Constants.OP_AUTH;
	}

	@Override
	public void action(Session session, Message proto) throws Exception {
		// 取出token验证
		LoginInfo info = proto.getLoginInfo();
		String uid = info.getUid();
		String devId = info.getDeviceId();
		String token = info.getToken();
		int platform = info.getPlatform();
		logger.info("auth {}", "uid="+uid + " , devId="+devId + " , token="+token + " , platform="+platform);
		//后面将基础信息持久化到内存数据库 mongodb 或者 sequiodb
		if(StringUtils.isEmpty(token)){
			session.writeAndClose(ProtobufBuilder.buildAuthRsp(ResultCodeEnum.NO_TOKEN, proto.getSeqId(),""));
			return;
		}
		//因为不同设备ID，同一个Uid ,它的sessionID也是不一样的
		//String chatId = SessionUtil.getSessionId(uid,devId);
		session.setSessionUniqueId(uid);
		SessionMap.sharedInstance().addSession(uid, session);
		session.write(ProtobufBuilder.buildAuthRsp(ResultCodeEnum.SUCCESS, proto.getSeqId(),uid));
	}

}
